#ifndef HTTP_SERVER_HPP
#define HTTP_SERVER_HPP

#include <iostream>
#include <pthread.h>
#include <signal.h>
#include "Log.hpp"
#include "TcpServer.hpp"
#include "Task.hpp"
#include "ThreadPool.hpp"

#define PORT 8081

class HttpServer
{
private:
    int _port;
    ThreadPool thread_pool;
    bool stop;
public:
    HttpServer(int port = PORT): _port(port), stop(false)    
    {}

    void InitServer()
    {
        // 忽略SIGPIPE信号，防止服务器在发送数据时，客户端已经关闭连接，导致服务器崩溃
        signal(SIGPIPE, SIG_IGN);
        // _tcp_svr = TcpServer::GetInstance(_port);
    }

    void Loop()
    {
        TcpServer* tsvr = TcpServer::GetInstance(_port);
        LOG(INFO, "LOOP START...");
        while(!stop)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int sock = accept(tsvr->GetListenSock(), (struct sockaddr*)&peer, &len);
            if(sock < 0)
            {
                continue;
            }
            LOG(INFO, "Get a new link!");
            Task task(sock);
            ThreadPool::GetInstance()->PushTask(task);
        }
    }

    ~HttpServer(){}
};

#endif